//
//  DeviceShareInviteVC.m
//  KEREN
//
//  Created by MW on 2023/4/9.
//

#import "DeviceShareInviteVC.h"
#import "KRChooseCell.h"
#import "DeviceShareVC.h"
@interface DeviceShareInviteVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) UILabel *dateLbl;
@property (nonatomic, strong) UITableView *alertTableView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, assign) int currentIndex;
@property (nonatomic, assign) int shareTime;
@property (nonatomic, assign) BOOL isShareDay;
@property (nonatomic, strong) UITextField *textfiled;
@end

@implementation DeviceShareInviteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //TODO :国际化
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"分享邀请"];
    [self setViewLayout];
    _currentIndex = 0;
    _shareTime = -1;
    _isShareDay = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //当键盘将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)deviceShare{
    WEAKSELF
    if(_currentIndex == 0){
        _shareTime = -1;
    }else{
        if(self.textfiled.text.length < 1 ||  [self.textfiled.text intValue] < 1){
            [[KRAlartManager shareInstance] showAlert:@"请输入分享时长或选择不限时"];
            return;
        }
        if(_isShareDay){
            _shareTime = [self.textfiled.text intValue] * 60 * 60 * 24;
        }else{
            _shareTime = [self.textfiled.text intValue] * 60 * 60;
        }
    }
    DeviceInfo *info = _deviceInfo;
    NSDictionary *parameters = @{@"ebike_id":@(info.Id),@"phone":_photoStr,@"share_time":@(_shareTime)};
    [NetworkingTool POST:Device_share_create parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                for(UIViewController *vc in weakSelf.navigationController.viewControllers){
                    if([vc isKindOfClass:[DeviceShareVC class]]){
                        [weakSelf.navigationController popToViewController:vc animated:YES];
                    }
                }               
            });
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)setViewLayout{
    DeviceInfo *deviceInfo = _deviceInfo;
    UILabel *nameLbl = [UILabel setLblText:deviceInfo.name font:Font(24) withColor:Black_Color inSubView:self.view];
    [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.navView.mas_bottom).offset(22);
    }];
    
    UIImageView *deviceImageView = [[UIImageView alloc] init];
    [self.view addSubview:deviceImageView];
    [deviceImageView sd_setImageWithURL:[NSURL URLWithString:deviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
    [deviceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(200);
        make.top.equalTo(nameLbl.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    UILabel *tipsLbl = [UILabel setLblText:@"将设备分享给" font:Font(14) withColor:Color_86898E inSubView:self.view];
    [tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(deviceImageView.mas_bottom).offset(10);
    }];
    //share_other
    for (int i = 0; i < 2; i ++) {
        UIView *view = [[UIView alloc] init];
        [self.view addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24 + i *(DEVICE_WIDTH - 48) / 2);
            make.width.offset((DEVICE_WIDTH - 48) / 2);
            make.height.offset(60);
            make.top.equalTo(tipsLbl.mas_bottom).offset(20);
        }];
        UIImageView *icon = [[UIImageView alloc] init];
        [view addSubview:icon];
        view.layer.cornerRadius = 25;
        view.clipsToBounds = YES;
        view.layer.borderWidth = 1;
        UILabel *label = [[UILabel alloc] init];
        label.font = Font(14);
        [view addSubview:label];
        if(i == 0){
            icon.image = [UIImage imageNamed:@"share_me"];
            view.layer.borderColor = Color_borderColor;
            [icon mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(view);
                make.left.offset(16);
                make.width.height.offset(16);
            }];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(34);
                make.centerY.equalTo(view);
            }];
            label.textColor = Black_Color;
            label.text = @"本机用户";
        }else{
            icon.image = [UIImage imageNamed:@"share_other"];
            view.layer.borderColor = Color_7ACC00.CGColor;
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-16);
                make.centerY.equalTo(view);
            }];

            [icon mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(view);
                make.right.equalTo(label.mas_left).offset(-2);
                make.width.height.offset(16);
            }];
            label.textColor = Color_7ACC00;
            label.text = _photoStr;
        }
    }
    UIImageView *shareToIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"share_to"]];
    [self.view addSubview:shareToIcon];
    [shareToIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipsLbl.mas_bottom).offset(20);
        make.width.height.offset(60);
        make.centerX.equalTo(self.view);
    }];
    
    UIView *deteView = [[UIView alloc] init];
    [self.view addSubview:deteView];
    [deteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(60);
        make.top.equalTo(shareToIcon.mas_bottom).offset(20);
        make.left.right.offset(0);
    }];
    deteView.backgroundColor = Whire_Color;
    deteView.userInteractionEnabled = YES;
    UILabel *datechooseLbl = [UILabel setLblText:@"时效选择" font:Font(16) withColor:Color_333333 inSubView:deteView];
    [datechooseLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.centerY.equalTo(deteView);
    }];

    UIImageView *rightIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Vector"]];
    [deteView addSubview:rightIcon];
    [rightIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.width.offset(8);
        make.height.offset(14);
        make.centerY.equalTo(deteView);
    }];
    _dateLbl = [UILabel setLblText:@"不限时" font:Font(14) withColor:Color_86898E inSubView:deteView];
    [_dateLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightIcon.mas_right).offset(-12);
        make.centerY.equalTo(deteView);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [deteView addGestureRecognizer:tap];
    
    UILabel *tipLbl = [UILabel setLblText:@"时间从被分享人接收邀请开始计算" font:Font(12) withColor:Color_86898E inSubView:self.view];
    [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(deteView.mas_bottom).offset(12);
        make.left.offset(24);
    }];
    
    UIButton *sendBtn = [UIButton setButtonWithTitle:@"发起邀请" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.top.equalTo(tipLbl.mas_bottom).offset(30);
    }];
    [sendBtn addTarget:self action:@selector(deviceShare) forControlEvents:UIControlEventTouchUpInside];
}


- (void)tapClick{
    UIWindow *window = UIApplication.sharedApplication.delegate.window;
    [window addSubview:self.backView];
    _whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT - 210 - 58 - BottomSpance_height, DEVICE_WIDTH, 210 + 58 + BottomSpance_height)];
    [_whiteView addSubview:self.alertTableView];

    if(_currentIndex == 1){
        _whiteView.frame = CGRectMake(0, DEVICE_HEIGHT - 300 - 58 - BottomSpance_height, DEVICE_WIDTH, 300 + 58 + BottomSpance_height);
        _whiteView.backgroundColor = Whire_Color;
        _alertTableView.frame = CGRectMake(0, 60, DEVICE_WIDTH, 240);
    }else{
        _whiteView.frame = CGRectMake(0, DEVICE_HEIGHT - 210 - 58 - BottomSpance_height, DEVICE_WIDTH, 210 + 58 + BottomSpance_height);
        _alertTableView.frame = CGRectMake(0, 60, DEVICE_WIDTH, 150);
    }

    _whiteView.backgroundColor = Whire_Color;
    _whiteView.layer.mask = [CAShapeLayer clipsToBounds:_whiteView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];

    [self.backView addSubview:_whiteView];
    UILabel *titleLbl = [[UILabel alloc] init];
    [_whiteView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.top.offset(15);
        make.height.offset(30);
    }];
    //TODO: 国际化
    titleLbl.text = @"时效选择";
    titleLbl.font = BFont(20);
    titleLbl.textColor = Black_Color;
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_whiteView addSubview:closeBtn];
    [closeBtn setImage:[UIImage imageNamed:@"NavBar_Default_Close"] forState:UIControlStateNormal];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-10);
        make.width.height.offset(40);
        make.top.offset(10);
    }];
    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *lineView = [UIView setLineViewWithframe:CGRectZero forinView:_whiteView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(1);
        make.top.offset(59);
    }];

    UIButton *sendBtn = [UIButton setButtonWithTitle:@"确认" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [_whiteView addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-BottomSpance_height);
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
    }];
    [sendBtn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewendEditing{
    [self.view endEditing:YES];
}

- (void)sendBtnClick{
    if(_currentIndex == 0){
        _dateLbl.text = @"不限时";
    }else{
        if(_isShareDay){
            _dateLbl.text = [NSString stringWithFormat:@"%@天",_textfiled.text];
        }else{
            _dateLbl.text = [NSString stringWithFormat:@"%@小时",_textfiled.text];
        }
    }
    [self close];
}

- (void)close{
    [_backView removeAllSubviews];
    [_backView removeFromSuperview];
    _backView = nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        return 60;
    }else{
        if(_currentIndex == 1){
            return 150;
        }else{
            return 60;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KRChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRChooseCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(_currentIndex == indexPath.row){
        cell.contentView.backgroundColor = Color_F6F6F6;
        cell.chooseBtn.selected = YES;
    }else{
        cell.contentView.backgroundColor = Whire_Color;
        cell.chooseBtn.selected = NO;
    }
    cell.chooseView.layer.cornerRadius = 15;
    cell.chooseView.clipsToBounds = YES;
    cell.chooseView.layer.borderColor = Color_86898E.CGColor;
    cell.chooseView.layer.borderWidth = 1;
    self.textfiled = cell.textField;
    cell.textField.clearButtonMode = UITextFieldViewModeAlways;
    UIButton *clean = [cell.textField valueForKey:@"_clearButton"];
    clean.frame = CGRectMake(0, 0, 60, 60);
    //key是固定的
    //clean.size = CGSizeMake(60, 60);
    [clean setImage:[UIImage imageNamed:@"clear"] forState:UIControlStateNormal];
    
    cell.changeShareType = ^(BOOL isDay) {
        self.isShareDay = isDay;
    };
    if(_currentIndex == 1 && indexPath.row == 1){
        cell.chooseView.hidden = NO;
        cell.textField.hidden = NO;

    }else{
        cell.chooseView.hidden = YES;
        cell.textField.hidden = YES;
    }
    if(indexPath.row == 0){
        cell.nameLbl.text = @"不限时";
    }else{
        cell.nameLbl.text = @"限时";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _currentIndex = (int)indexPath.row;
    if(indexPath.row == 1){
        _whiteView.frame = CGRectMake(0, DEVICE_HEIGHT - 300 - 58 - BottomSpance_height, DEVICE_WIDTH, 300 + 58 + BottomSpance_height);
        _whiteView.backgroundColor = Whire_Color;
        _alertTableView.frame = CGRectMake(0, 60, DEVICE_WIDTH, 240);
        _whiteView.layer.mask = [CAShapeLayer clipsToBounds:_whiteView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];
    }else{
        _whiteView.frame = CGRectMake(0, DEVICE_HEIGHT - 210 - 58 - BottomSpance_height, DEVICE_WIDTH, 210 + 58 + BottomSpance_height);
        _alertTableView.frame = CGRectMake(0, 60, DEVICE_WIDTH, 150);
        _whiteView.layer.mask = [CAShapeLayer clipsToBounds:_whiteView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];
        self.shareTime = -1;
    }
    [self.alertTableView reloadData];
}

- (UITableView *)alertTableView{
    if(!_alertTableView){
        _alertTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, DEVICE_WIDTH, 150)];
        _alertTableView.backgroundColor = Whire_Color;
        _alertTableView.delegate = self;
        _alertTableView.dataSource = self;
        _alertTableView.rowHeight = 60;
        _alertTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_alertTableView registerNib:[UINib nibWithNibName:@"KRChooseCell" bundle:nil] forCellReuseIdentifier:@"KRChooseCell"];
    }
    return _alertTableView;
}

-(void)keyboardWillShow:(NSNotification *)notification{
    WEAKSELF
    CGRect keyboardBounds;
    [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    //拿到键盘的高度
    CGFloat keyboardHeight = keyboardBounds.size.height;
    
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        weakSelf.backView.transform = CGAffineTransformMakeTranslation(0, -keyboardHeight);
    }];
}
 
 
//当键盘退出
-(void)keyboardWillHide:(NSNotification *)notification{
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.backView.transform = CGAffineTransformIdentity;

    }];
}

-(UIView *)backView{
    if(!_backView){
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)];
        _backView.backgroundColor = rgba(0, 0, 0, 0.6);
    }
    return _backView;
}



@end
